<template>
  <div class="services-page">
    <div class="page-header">
      <h1>服务项目管理</h1>
      <p class="subtitle">管理服务项目，包括任务周期、时间设置、提醒配置等</p>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索服务项目..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="action-section">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          添加服务项目
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="services"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="serviceName" label="服务名称" width="200">
          <template #default="{ row }">
            {{ row.serviceName }}
          </template>
        </el-table-column>
        <el-table-column label="完成周期" width="120">
          <template #default="{ row }">
            {{ getCycleText(row.completionCycle) }}
            <span v-if="row.cycleValue > 1">（{{ row.cycleValue }}）</span>
          </template>
        </el-table-column>
        <el-table-column label="时间范围" width="200">
          <template #default="{ row }">
            <div v-if="row.startDate || row.endDate">
              {{ formatDate(row.startDate) }} ~ {{ formatDate(row.endDate) }}
            </div>
            <span v-else class="text-muted">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="reminderFrequency" label="提醒频率" width="120">
          <template #default="{ row }">
            {{ row.reminderFrequency || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="客户数量" width="100">
          <template #default="{ row }">
            {{ row._count?.clientAssignments || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="!!row.deletedAt"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑服务项目' : '添加服务项目'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
        </el-form-item>
        
        <el-form-item label="完成周期" prop="completionCycle">
          <select
            v-model="form.completionCycle"
            class="el-select-style"
          >
            <option value="">请选择完成周期</option>
            <option value="daily">每日</option>
            <option value="weekly">每周</option>
            <option value="monthly">每月</option>
            <option value="quarterly">每季度</option>
            <option value="yearly">每年</option>
          </select>
          <el-input-number
            v-model="form.cycleValue"
            :min="1"
            :max="255"
            style="width: 120px; margin-left: 12px"
            placeholder="周期值"
          />
        </el-form-item>
        
        <el-form-item label="开始时间">
          <input
            v-model="form.startDateStr"
            type="date"
            class="el-input-style"
            placeholder="选择开始时间"
          />
        </el-form-item>

        <el-form-item label="结束时间">
          <input
            v-model="form.endDateStr"
            type="date"
            class="el-input-style"
            placeholder="选择结束时间"
          />
        </el-form-item>
        
        <el-form-item label="提醒频率">
          <el-input v-model="form.reminderFrequency" placeholder="如：每天、每周一、每月1号等" />
        </el-form-item>
        
        <el-form-item label="提醒内容">
          <el-input
            v-model="form.reminderContent"
            type="textarea"
            :rows="3"
            placeholder="请输入提醒内容"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Message, MessageBox } from '@/utils/message';
import { Search, Plus, Refresh } from '@element-plus/icons-vue';
import { trpc } from '../../utils/trpc';

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const services = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 表单数据
const form = reactive({
  id: 0,
  serviceName: '',
  completionCycle: 'monthly',
  cycleValue: 1,
  startDate: null as Date | null,
  endDate: null as Date | null,
  startDateStr: '',
  endDateStr: '',
  reminderFrequency: '',
  reminderContent: '',
});

// 表单验证规则
const formRules = {
  serviceName: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 1, max: 100, message: '服务名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  completionCycle: [
    { required: true, message: '请选择完成周期', trigger: 'change' }
  ],
};

// 获取周期文本
const getCycleText = (cycle: string) => {
  const cycleMap: Record<string, string> = {
    daily: '每日',
    weekly: '每周',
    monthly: '每月',
    quarterly: '每季度',
    yearly: '每年',
  };
  return cycleMap[cycle] || cycle;
};

// 格式化日期
const formatDate = (dateString: string | null) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleDateString();
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await trpc.service.list.query({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value || undefined,
    });
    
    if (response.success) {
      services.value = response.data.data;
      total.value = response.data.pagination.total;
    } else {
      Message.error(response.message || '加载数据失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    Message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadData();
};


// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false;
  resetForm();
  console.log('创建对话框打开，form.completionCycle:', form.completionCycle);
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (row: any) => {
  isEdit.value = true;
  form.id = row.id;
  form.serviceName = row.serviceName;
  form.completionCycle = row.completionCycle;
  form.cycleValue = row.cycleValue;
  form.startDate = row.startDate ? new Date(row.startDate) : null;
  form.endDate = row.endDate ? new Date(row.endDate) : null;
  form.startDateStr = row.startDate ? new Date(row.startDate).toISOString().split('T')[0] : '';
  form.endDateStr = row.endDate ? new Date(row.endDate).toISOString().split('T')[0] : '';
  form.reminderFrequency = row.reminderFrequency || '';
  form.reminderContent = row.reminderContent || '';
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.id = 0;
  form.serviceName = '';
  form.completionCycle = 'monthly';
  form.cycleValue = 1;
  form.startDate = null;
  form.endDate = null;
  form.startDateStr = '';
  form.endDateStr = '';
  form.reminderFrequency = '';
  form.reminderContent = '';
  console.log('表单重置完成，form.completionCycle:', form.completionCycle);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 验证日期逻辑
    if (form.startDateStr && form.endDateStr && form.startDateStr >= form.endDateStr) {
      Message.error('开始时间必须早于结束时间');
      return;
    }

    submitting.value = true;

    const submitData = {
      serviceName: form.serviceName,
      completionCycle: form.completionCycle,
      cycleValue: form.cycleValue,
      startDate: form.startDateStr ? new Date(form.startDateStr).toISOString() : undefined,
      endDate: form.endDateStr ? new Date(form.endDateStr).toISOString() : undefined,
      reminderFrequency: form.reminderFrequency || undefined,
      reminderContent: form.reminderContent || undefined,
    };
    
    let response;
    if (isEdit.value) {
      response = await trpc.service.update.mutate({
        id: form.id,
        ...submitData,
      });
    } else {
      response = await trpc.service.create.mutate(submitData);
    }
    
    if (response.success) {
      Message.success(response.message || (isEdit.value ? '更新成功' : '创建成功'));
      dialogVisible.value = false;
      loadData();
    } else {
      Message.error(response.message || (isEdit.value ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
    Message.error('操作失败');
  } finally {
    submitting.value = false;
  }
};

// 删除处理
const handleDelete = async (row: any) => {
  try {
    await MessageBox.confirm(
      `确定要永久删除服务项目 "${row.serviceName}" 吗？此操作将级联删除相关的分配关系和工作日志，且不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await trpc.service.delete.mutate({ id: row.id });
    
    if (response.success) {
      Message.success(response.message || '删除成功');
      loadData();
    } else {
      Message.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      Message.error('删除失败');
    }
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.services-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-section {
  flex: 1;
  min-width: 300px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.text-muted {
  color: #8c8c8c;
}

/* 已删除记录样式 */
.deleted-record {
  color: #999;
  text-decoration: line-through;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section {
    min-width: auto;
  }
  
  .action-section {
    justify-content: center;
  }
}

/* 原生select样式，模仿Element Plus */
.el-select-style {
  width: 200px;
  height: 32px;
  padding: 0 11px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-select-style:hover {
  border-color: #c0c4cc;
}

.el-select-style:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.el-select-style option {
  padding: 8px 12px;
  color: #606266;
  background-color: #fff;
}

.el-select-style option:hover {
  background-color: #f5f7fa;
}

/* 原生input样式，模仿Element Plus */
.el-input-style {
  width: 200px;
  height: 32px;
  padding: 0 11px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-input-style:hover {
  border-color: #c0c4cc;
}

.el-input-style:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
